<?php

abstract class WebResponder implements IWebResponder {
	function callAndPassExceptionToResponder($callable, $args) {
		try {
			return call_user_func_array($callable, $args);
		} catch (Exception $e) {
			return $this->exceptionHandler($e);
		}
	}
	
	// abstract function responseForRequest(IWebRequest $r);
	
	static function shouldBeUsedForRequest(IWebRequest $r) {
		return true;
	}
	
	public function exceptionHandler($e) {
		if ($e instanceof WebException)
			return $e->response();
		
		$class = get_class($e);
		do {
			$m = null;
			$newClass = $class;
			$newClass[0] = strtoupper($newClass[0]);
			try { $m = new ReflectionMethod($this, 'handle' . $newClass); }
			catch (ReflectionException $e) { }
			
			if ($m)
				return $m->invokeArgs($this, array($e));
			
			$class = get_parent_class($class);
		} while ($class);
		
		throw $e;
	}
	
	public function handleException($e) {
		throw $e;
	}
	
	public function handleCNotFoundException($e) {
		return new WebErrorResponse('404 Not Found');
	}
	
	public function handleCNotAllowedException($e) {
		return new WebErrorResponse('403 Forbidden');
	}
}

?>